package com.teamin.web.interceptor;

import com.mysql.cj.core.util.StringUtils;
import com.teamin.service.JwtService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private JwtService jwtService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String session = request.getSession().getId();
		System.out.println("------------------------------sessionId="+session);
		String requestURI = request.getRequestURI();
//		if (requestURI.equals("/error")) {
//			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorConfig.NOT_FOUND));
//		}
		// Integer personId =
		// ServletRequestUtils.getIntParameter(request,"personId", 0);
		logger.info("we are Intercepting the Request RequestURI::" + requestURI);

		// token字符串
		String authHeader = request.getHeader(jwtService.getAUTH_HEADER());

		Claims claims = jwtService.readToken(authHeader);

		// token中携带的登陆信息转换成map类型
		@SuppressWarnings("unchecked")
		Map<String, String> loginInfo = (Map<String, String>) claims.get("loginInfo");

		// 把token携带的登陆信息存入attribute
		request.setAttribute("loginInfo", loginInfo);

		if(!StringUtils.isNullOrEmpty(authHeader)) {
			String[] sp = authHeader.split("\\.");
			if(sp.length > 1) {
				request.setAttribute("userFlag", sp[1]);
			}
		}

		// 把登陆用户的userid设到request Attribute
		request.setAttribute("loginUserId", loginInfo.get("userId"));

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model)
			throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3)
			throws Exception {
	}
}
